cc.Class({
    extends: cc.Component,

    properties: {
        gameRoot:{
            default:null,
            type:cc.Node
        },
        
        prepareRoot:{
            default:null,
            type:cc.Node   
        },
        
        _myMJArr:[],
        _myChupai:[],
        _holds:[],
        _folds:[],
        _Chupai:[],
        _yafen:[],
        _qiangNotice:[],
        chupaiNum:0,

        _qiangzhuang:null,
        _jiaofen:null,
        _notice:null,
        _paidui:null,
        _paiduiItem:null,
        _zhezhao:null,
        // moveObj:[]
    },
    onLoad: function () {
        console.log("MjRoomOnLoad");
        if(!cc.sys.isNative && cc.sys.isMobile){
            var cvs = this.node.getComponent(cc.Canvas);
            cvs.fitHeight = true;
            cvs.fitWidth = true
        };
        if(!cc.vv){
            cc.director.loadScene("loading");
            return
        };
        // cc.vv.MjGame = this;
        this.node.addComponent("MjGameOver");
        this.node.addComponent("MjRoom");
        this.node.addComponent("TimePointer");
        this.node.addComponent("MjGameResult");
        this.node.addComponent("Chat");
        this.node.addComponent("Alert");
        // this.node.addComponent("Folds");
        // this.node.addComponent("ReplayCtrl");
        this.node.addComponent("PopupMgr");
        this.node.addComponent("ReConnect");
        this.node.addComponent("Voice");
        this.node.addComponent("UserInfoShow");
        // debugger;
        this.initView();
        this.initEventHandlers();
        
        this.gameRoot.active = false;
        this.prepareRoot.active = true;
        this.onGameBeign();
        cc.vv.audioMgr.playBGM("game_bg.mp3")
    },
    
    initView:function(){
        //搜索需要的子节点
        var gameChild = this.gameRoot;
        var myselfChild = gameChild.getChildByName("myself");
        var myholds = myselfChild.getChildByName("holds");
        // 自己手牌
        for(var i = 0; i < myholds.childrenCount; ++i){
            var sprite = myholds.children[i].children[0].getChildByName("pai").getComponent(cc.Sprite);
            this._myMJArr.push(sprite);
            sprite.spriteFrame = null;
            // 保存初始位置用于复原
            sprite.node.parent.chushiY=sprite.node.parent.y;
            cc.vv.utils.addClickEvent(myholds.children[i].children[0],this.node,"MjGame","onMJClicked")
        };
        var realwidth = cc.director.getVisibleSize().width;
        myholds.scaleX *= realwidth/1280;
        myholds.scaleY *= realwidth/1280;  
        
        var sides = ["myself","right","up","left"];
        for(var i = 0; i < sides.length; ++i){
            var side = sides[i];     
            var sideChild = gameChild.getChildByName(side);
            this._holds.push(sideChild.getChildByName("holds"));//每个人的手牌(未配牌)
            this._folds.push(sideChild.getChildByName("folds"));//每个人的配牌（已配牌未亮）
            this._Chupai.push(sideChild.getChildByName("ChuPai"));//每个人的出牌（亮牌）
            this._qiangNotice.push(sideChild.getChildByName("qiangzhuang"))//每个人的抢庄选择
            this._yafen.push(sideChild.getChildByName("jiaofen"))//每个人的叫分
        };
        // 出牌按钮
        var chupaiBt=gameChild.getChildByName("btnChu");
        chupaiBt.active=false;
        // 不可点击时自动转灰色
        chupaiBt.enableAutoGrayEffect=true;
        cc.vv.utils.addClickEvent(chupaiBt,this.node,"MjGame","onChuClicked");
        // 配牌提示
        this._notice=gameChild.getChildByName("notice");
        // 牌堆
        this._paidui=gameChild.getChildByName("paidui");
        this._paiduiItem=this._paidui.children[0];
        
        // 抢庄按钮
        this._qiangzhuang=gameChild.getChildByName("qiangzhuang");
        for (var i = 0; i < this._qiangzhuang.childrenCount; i++) {
            var bt=this._qiangzhuang.children[i];
            cc.vv.utils.addClickEvent(bt,this.node,"MjGame","onBtnQiangClick")
        };
        // 叫分界面
        this._jiaofen=gameChild.getChildByName("jiaofen");
        // 准备按钮
        var btnReady=this.gameRoot.getChildByName("btnReady");
        cc.vv.utils.addClickEvent(btnReady,this.node,"MjGame","onReadyClicked");
        // 桌布遮罩（发牌翻牌时禁止用户操作）
        this._zhezhao=gameChild.getChildByName("zhezhao")
    },
    // 隐藏出牌（亮牌）
    hideChupai:function(){
        console.log("hideChupai");
        for(var i = 0; i < this._Chupai.length; ++i){
            this._Chupai[i].active = false;
            if (i==0) {
                for (var j = 0; j < 4; j++) {
                    var sprite=this._Chupai[i].children[j].getComponent(cc.Sprite);
                    sprite.spriteFrame=cc.vv.mjmgr.emptySprite
                }
            }else{
                for (var j = 0; j < 4; j++) {
                    var sprite=this._Chupai[i].children[j].children[0].getComponent(cc.Sprite);
                    sprite.spriteFrame=cc.vv.mjmgr.emptySprite
                }
            };
            
            // 隐藏牌型
            var icon=this._Chupai[i].getChildByName("icon");
            icon.active=false;
            icon.children[0].active=false;
            icon.children[1].active=false;
            var name=this._Chupai[i].getChildByName("name");
            name.active=false;
            name.children[0].active=false;
            name.children[1].active=false
        }        
    },
    // 隐藏配牌
    hideFolds:function(){
        console.log("hideFolds");
        for(var i = 0; i < this._folds.length; ++i){
            this._folds[i].active = false
        }        
    },
    // 隐藏手牌
    hideHolds:function(){
        console.log("hideHolds");
        for(var i = 0; i < this._holds.length; ++i){
            this._holds[i].active = false
        };
        // 自己手牌处理
        for (var i = 0; i < this._myMJArr.length; i++) {
            var node=this._myMJArr[i].node.parent;
            node.getChildByName("dise").active=false;
            node.getChildByName("pai").getComponent(cc.Sprite).spriteFrame=cc.vv.mjmgr.emptySprite;
            node.y=node.chushiY
        }
    },
    // 隐藏抢庄按钮
    hideQiangZhuang:function(){
        console.log("hideQiangZhuang");
        this._qiangzhuang.active=false  
    },
    // 隐藏抢庄选择
    hideQiangNotice:function(){
        console.log("hideQiangNotice");
        for(var i = 0; i < this._qiangNotice.length; ++i){
            var node=this._qiangNotice[i];
            this.doFadeOut(node,3,function(node){
                node.active=false;
                node.children[0].active=false;
                node.children[1].active=false
            })
        }        
    },
    // 隐藏压分
    hideYafen:function(){
        console.log("hideYafen");
        for(var i = 0; i < this._yafen.length; ++i){
            var node=this._yafen[i];
            node.children[0].getChildByName("fen").getComponent(cc.Label).string="";
            node.children[1].getChildByName("fen").getComponent(cc.Label).string="";
            node.active = false
        }        
    },
    initEventHandlers:function(){
        cc.vv.gameNetMgr.dataEventHandler = this.node;
        //初始化事件监听器
        var self = this;
        this.node.on('game_begin',function(data){
            console.log("game_begin",data.detail);
            self.onGameBeign();
            cc.vv.audioMgr.playSFX("start.mp3")
        });
        this.node.on('game_qiangzhuang',function(data){
            console.log("game_qiangzhuang",data.detail);
            self.showQiangZhuang()
        });
        this.node.on('game_qiangzhuang_notify',function(data){
            console.log("game_qiangzhuang_notify",data.detail);
            self.initQiangNotice(data.detail)
        });
        this.node.on('game_dingzhuang',function(data){
            console.log("game_dingzhuang",data.detail);
            self.hideQiangNotice()
        });
        this.node.on('game_jiaofen',function(data){
            console.log("game_jiaofen",data.detail);
            // 重置叫分状态
            self.node.emit("initJiaofen");
            self.showJiaofen();
            self.showYafen()
        });
        this.node.on('game_jiaofen_notify',function(data){
            console.log("game_jiaofen_notify",data.detail);
            self.initJiaofen(data.detail)
        });
        this.node.on('game_jiaofen_end_notify',function(data){
            console.log("game_jiaofen_end_notify",data.detail);
            
        });
        this.node.on('game_holds',function(data){
            console.log("game_holds",data.detail);
        });
        this.node.on('game_peipai',function(data){
            console.log("game_peipai",data.detail)
            
        });
        this.node.on('game_peipai_notify',function(data){
            console.log("game_peipai_notify",data.detail);
            var seatIndex=data.detail.seatindex;
            var localIndex=cc.vv.gameNetMgr.getLocalIndex(seatIndex);
            // 自己展示出牌。其他人展示配牌
            if (localIndex==0) {
                self.showChupai(0,self._myChupai)
            }else{
                self.showFolds(localIndex)
            }
        });
        this.node.on('game_peipai_result_notify',function(data){
            console.log("game_peipai_result_notify",data.detail);
            var pais=data.detail.peipaione.concat(data.detail.peipaitwo);
            self.showChupai(0,pais)
        });
        this.node.on('game_playing',function(data){
            console.log("game_playing",data.detail);
            self._notice.active=false;
            // 丢色子
            self.doSezi()
        });
        this.node.on('game_showpai',function(data){
            console.log("game_showpai",data.detail);
            self.showDipai()
        });
        this.node.on('game_over',function(data){
            console.log("game_over/mjgame",data.detail);
            var data=data.detail;
            // 逐个翻牌
            self.doFanpai(data)
        });
        // this.node.on('reconnectInit',function(data){
        //     console.log("reconnectInit/mjgame",data.detail);
        //     self.onGameBeign()
        // })
    },
    // 结束时翻牌
    doFanpai:function(data){
        console.log("doFanpai",data);
        // 按配牌翻牌（同时翻第一副，隔三秒同时翻第二副，翻那副牌显示那副牌点数,最后显示扣分，遇到自己则跳过翻牌直接显示点数）
        var startIndex=cc.vv.gameNetMgr.button;
        // 标记翻盘是第一副还是第二副
        var peipaiNum=0;
        var self=this;
        // 开启遮罩
        this._zhezhao.active=true;
        var fn=function(){
            peipaiNum++;
            for (var i = 0; i < data.length; i++) {
                var seatData=data[i];
                var seatIndex=cc.vv.gameNetMgr.getSeatIndexByID(seatData.userId);
                var localIndex=cc.vv.gameNetMgr.getLocalIndex(seatIndex);
                if (peipaiNum==1) {
                    var chupai=seatData.peipaitwo
                }else{
                    var chupai=seatData.peipaione
                };
                self.showChupai(localIndex,chupai,seatData,peipaiNum)
            };
            setTimeout(function(){
                if (peipaiNum<2) {
                    setTimeout(fn,2000)
                }else{
                    setTimeout(function(){
                        // 关闭遮罩
                        self._zhezhao.active=false;
                        // 显示准备按钮
                        var btnReady=self.gameRoot.getChildByName("btnReady");
                        btnReady.active=true;
                        // 发送事件刷新坐席(原有的结束立马刷新废弃)
                        self.node.emit("game_over_initseats")
                        // 发送事件播放音乐
                        self.node.emit("game_over_music")
                    },2000);
                    return
                }
            },1000)
        };
        fn()
    },
    // 展示亮牌隐藏手牌和配牌
    showChupai:function(localIndex,pais,seatData,peipaiNum){
        console.log("showChupai+peipaiNum",peipaiNum);
        this._folds[localIndex].active=false;
        this._holds[localIndex].active=false;
        var chupai=this._Chupai[localIndex];
        chupai.active=true;
        var self=this;
        // peipaiNum:1翻前两牌,2翻后两牌
        if (peipaiNum==1) {
            // 控制要显示的节点起始位置
            var qishiNum=2
        }else{
            var qishiNum=0
        };
        for ( var i=0 ; i < pais.length; i++) {
        // 自己没有翻牌
            if (localIndex==0) {
                var sprite=chupai.children[i+qishiNum].getComponent(cc.Sprite);
                this.setSpriteFrameByMJID(sprite,pais[i]);
                this.showPaixing(chupai,seatData,peipaiNum)
            }else{
                var sprite=chupai.children[i+qishiNum].children[0].getComponent(cc.Sprite);
                this.setSpriteFrameByMJID(sprite,pais[i]);
                var node=sprite.node.parent;
                // 保存数据到节点上，定时器回调用
                node.chupai=chupai;
                node.seatData=seatData;
                node.peipaiNum=peipaiNum;
                // 加翻牌动作
                this.addXuanzhuan(node,function(node){
                    self.showPaixing(node.chupai,node.seatData,node.peipaiNum)
                })
            }
        }
    },
    // 展示牌型点数结果
    showPaixing:function(chupai,seatData,paiTypeNum){
        // console.log("showPaixing");
        if (seatData) {
            // console.log("有牌型");
            if (paiTypeNum==1) {
                // 控制配牌图像数据，点数数据，节点起始位置
                var paiTypeData=seatData.peitypetwo;
                var tailnumData=seatData.tailnumtwo;
                var qishiNum=1
            }else{
                var paiTypeData=seatData.peitypeone;
                var tailnumData=seatData.tailnumone;
                var qishiNum=0
            }
            if (paiTypeData>0) {
                var spriteFrame=cc.vv.mjmgr.getPaixingSpriteFrameByNum(paiTypeData-1);
                var icon=chupai.getChildByName("icon");
                icon.children[qishiNum].getComponent(cc.Sprite).spriteFrame=spriteFrame;
                icon.active=true;
                icon.children[qishiNum].active=true;
                this.doFadeIn(icon.children[qishiNum],1)
            }else{
                var name=chupai.getChildByName("name");
                name.children[qishiNum].getComponent(cc.Sprite).spriteFrame=cc.vv.mjmgr.getPaixingNumSpriteFrameByNum(tailnumData);
                name.active=true;
                name.children[qishiNum].active=true;
                this.doFadeIn(name.children[qishiNum],1)
            }
        }
    },
    // 展示配牌
    showFolds:function(localIndex){
        console.log("showFolds",localIndex);
        this._holds[localIndex].active=false;
        this._folds[localIndex].active=true
    },
    // 展示手牌
    showHolds:function(localIndex,pais){
        console.log("showHolds localIndex",localIndex,"pais",pais);
        var holds=this._holds[localIndex];
        holds.active=true;
        // 自己才有手牌显示，其他人背面展示
        if (localIndex==0) {
            for (var i = 0; i < pais.length; i++) {
                var node=holds.children[i].children[0].getChildByName("pai");
                node.mjid=pais[i];
                // isChoose标记是否被选中
                node.parent.isChoose=false;
                var sprite=node.getComponent(cc.Sprite);
                this.setSpriteFrameByMJID(sprite,pais[i]);
                this.addXuanzhuan(sprite.node.parent.parent)
            }
        }else{
            for (var i = 0; i < holds.childrenCount; i++) {
                var sprite=holds.children[i].getComponent(cc.Sprite);
                sprite.spriteFrame=cc.vv.mjmgr.emptySprite
            }
        }
    },
    // 展示抢庄按钮
    showQiangZhuang:function(){
        console.log("showQiangZhuang");
        var myData=cc.vv.gameNetMgr.getSelfData();
        if (myData.qiangzhuang==-1) {
            this._qiangzhuang.active=true;
            this.doScale(this._qiangzhuang)
        }
    },
    // 展示叫分界面
    showJiaofen:function(){
        console.log("showJiaofen");
        // 提示信息(庄家才显示)
        if (cc.vv.gameNetMgr.button==cc.vv.gameNetMgr.seatIndex) {
            this._notice.active=true
        };
        // 庄家没有叫分
        if (cc.vv.gameNetMgr.button==cc.vv.gameNetMgr.seatIndex) {
            console.log("庄家不能叫分");
            return
        };
        // 已经叫的也不显示
        var myData=cc.vv.gameNetMgr.getSelfData();
        if (myData.scoreone>=0||myData.scoretwo>=0) {
            console.log("自己已经叫分");
            return
        };
        console.log("展示叫分界面");
        this._jiaofen.active=true
    },
    // 展示叫分显示(这个只控制叫分阶段时显示，和initjiaofen功能类似，initjiaofen能显示数据)
    showYafen:function(){
        console.log("showYafen");
        // 庄家没有叫分
        var localIndex=cc.vv.gameNetMgr.getLocalIndex(cc.vv.gameNetMgr.button);
        for (var i = 0; i < this._yafen.length; i++) {
            var node=this._yafen[i];
            if (i==localIndex) {
                node.active=false
            }else{
                node.active=true;
                this.doFadeIn(node,1)
            }
        }
    },
    // 十六张底牌显示
    showDipai:function(isOnlyShow){
        console.log("showDipai");
        // 先移除牌堆子节点（后面根据需要加）
        this._paidui.removeAllChildren();
        var pais=cc.vv.gameNetMgr.showpai;
        // isOnlyShow:是否单纯显示标记(不做发牌动画)
        if (isOnlyShow) {
            // 单纯展示的加牌
            if (pais.length==0||!pais) {
                var paiNum=16
            }else{
                var paiNum=0
            }
        }else{
            // 加牌下面做发牌效果
            if (pais.length==0||!pais) {
                var paiNum=32
            }else{
                var paiNum=16
            }
        };
        // 根据paiNum控制加多少底牌子节点
        for (var i = 0; i < paiNum; i++) {
            var node = cc.instantiate(this._paiduiItem);
            this._paidui.addChild(node)
        };
        
        // 有底牌（根据牌数据展示）
        for (var i = 0; i < pais.length; i++) {
            var node = cc.instantiate(this._paiduiItem);
            this._paidui.addChild(node);
            var sprite=node.getComponent(cc.Sprite);
            this.setSpriteFrameByMJID(sprite,pais[i])
        };
        this._paidui.active=true
    },
    // playEfx:function(index,name){
    //     this._playEfxs[index].node.active = true;
    //     this._playEfxs[index].play(name);
    // },
    onGameBeign:function(){
        console.log("onGameBeign");
        // for(var i = 0; i < this._playEfxs.length; ++i){
        //     this._playEfxs[i].node.active = false
        // };
        // 未开始游戏则不往下执行刷新游戏界面
        if(cc.vv.gameNetMgr.gamestate == ""||cc.vv.gameNetMgr.gamestate == "idle"){
            return
        };
        this._paidui.active=false;
        // 隐藏出牌，手牌，配牌，压分
        this.hideChupai();
        this.hideHolds();
        this.hideFolds();
        this.hideYafen();
        this._jiaofen.active=false;
        this.gameRoot.active = true;
        this.prepareRoot.active = false;
        
        // 加底牌(是否已经过了发牌阶段)
        if (cc.vv.gameNetMgr.gamestate=="qiangzhuang"||cc.vv.gameNetMgr.gamestate=="jiaofen"||cc.vv.gameNetMgr.gamestate=="begin") {
            this.showDipai()
        }else{
            this.showDipai(true)
        };
        // 抢庄显示
        if (cc.vv.gameNetMgr.gamestate=="qiangzhuang") {
            // 刷新玩家抢庄显示
            this.initQiangNotice();
            this.showQiangZhuang()
        };
        // 刷新玩家叫分显示
        this.initJiaofen();
       // 叫分和begin时不显示手牌
        if (cc.vv.gameNetMgr.gamestate=="jiaofen") {
            this.showJiaofen();
            this.showYafen()
        };
        // 未开始不发牌
        if (cc.vv.gameNetMgr.gamestate!="playing") {return};
        // 手牌更新
        this.initMahjongs()
    },
    // 手牌点击
    onMJClicked:function(event){
        console.log("onMJClicked");
        if(event.touch.getID() && event.touch.getID() != 0){
            console.log("多个手指点击");
            return
        };
       
        var node=event.target;
        // 已选则下降，未选则上升，同时改变标记和选中数量（控制能否出牌用）
        if (node.isChoose) {
            node.y-=25;
            node.getChildByName("dise").active=false;
            node.isChoose=!node.isChoose;
            this.chupaiNum--
        }else if (this.chupaiNum<2) {
            node.y+=25;
            node.getChildByName("dise").active=true;
            node.isChoose=!node.isChoose;
            this.chupaiNum++
        };
        this.changChuBt()
    },
    // 改变出牌按钮状态
    changChuBt:function(){
        console.log("changChuBt");
        var btnChu=this.gameRoot.getChildByName("btnChu").getComponent(cc.Button);
        if (this.chupaiNum==2) {
            console.log("可出牌",this.chupaiNum);
            btnChu.interactable=true;
            var sprite=btnChu.node.getComponent(cc.Sprite);
            sprite.spriteFrame=btnChu.normalSprite
        }else{
            console.log("不可出牌",this.chupaiNum);
            btnChu.interactable=false;
            var sprite=btnChu.node.getComponent(cc.Sprite)
        }
    },
    // 出牌按钮点击
    onChuClicked:function(event){
        console.log("onChuClicked");
        // 查找被选中的牌
        var paiOne=[];
        var paiTwo=[];
        for (var i = 0; i < this._myMJArr.length; i++) {
            var sprite=this._myMJArr[i];
            if (sprite.node.parent.isChoose) {
                paiOne.push(sprite.node.mjid)
            }else{
                paiTwo.push(sprite.node.mjid)
            }
        };
        // 保存出牌用于自己展示
        var self=this;
        this._myChupai=paiOne.concat(paiTwo);
        cc.vv.net.send("peipai",{paiOne:paiOne,paiTwo:paiTwo},function(){
            // 在线才发送
            // 隐藏提示和按钮
            event.target.active=false;
            self.chupaiNum=0
        })
    },
    // 抢庄按钮点击
    onBtnQiangClick:function(event){
        console.log("onBtnQiangClick");
        // 是否大结算
        var self=this;
        if (event.target.name=="btn_qiang") {
            cc.vv.net.send("qiangzhuang",{qiangzhuang:1},function(){
                self._qiangzhuang.active=false
            })
        }else{
            cc.vv.net.send("qiangzhuang",{qiangzhuang:0},function(){
                self._qiangzhuang.active=false
            })
        }
    },
    // 准备按钮点击
    onReadyClicked:function(event){
        console.log("onReadyClicked");
        // 是否大结算
        if (cc.vv.gameNetMgr.isEnd) {
            this.node.emit("game_end");
        }else{
            cc.vv.net.send("ready")
        };
        event.target.active=false
    },
    // 玩家抢庄显示
    initQiangNotice:function(data){
        console.log("initQiangNotice",data);
        if (data) {
            var localIndex=cc.vv.gameNetMgr.getLocalIndex(data.seatindex);
            var node=this._qiangNotice[localIndex];
            node.active=true;
            if (data.qiangzhuang==1) {
                node.children[0].active=true;
                node.children[1].active=false
            }else if (data.qiangzhuang==0){
                node.children[1].active=true;
                node.children[0].active=false
            }
        }else{
            var seats=cc.vv.gameNetMgr.seats;
            for (var i = 0; i < seats.length; i++) {
                var localIndex=cc.vv.gameNetMgr.getLocalIndex(seats[i].seatindex);
                var node=this._qiangNotice[localIndex];
                node.active=true;
                if (seats[i].qiangzhuang==1) {
                    node.children[0].active=true;
                    node.children[1].active=false
                }else if (seats[i].qiangzhuang==0){
                    node.children[1].active=true;
                    node.children[0].active=false
                }else{
                    node.children[1].active=false;
                    node.children[0].active=false
                }
            }
        }
    },
    // 玩家叫分显示
    initJiaofen:function(data){
        console.log("initJiaofen",data);
        if (data) {
            // 单个更新
            var localIndex=cc.vv.gameNetMgr.getLocalIndex(data.seatindex);
            var node=this._yafen[localIndex];
            node.active=true;
            node.children[0].getChildByName("fen").getComponent(cc.Label).string=data.fenOne;
            node.children[1].getChildByName("fen").getComponent(cc.Label).string=data.fenTwo
        }else{
            // 全部更新
            var seats = cc.vv.gameNetMgr.seats;
            for (var i = 0; i < seats.length; i++) {
                var seatData=seats[i];
                // 是否有叫分
                if (seatData.scoreone>=0) {
                    console.log("有叫分");
                    this.initJiaofen({seatindex:seatData.seatindex,fenOne:seatData.scoreone,fenTwo:seatData.scoretwo})
                }
            }
        }
    },
    initMahjongs:function(){
        console.log('initMahjongs');
        var seats = cc.vv.gameNetMgr.seats;
        for (var i = 0; i < seats.length; i++) {
            var seatData=seats[i];
            var localIndex=cc.vv.gameNetMgr.getLocalIndex(seatData.seatindex);
            // 有手牌则刷新手牌,有配牌则显示配牌,有亮牌则显示亮牌
            if (seatData.chupai&&seatData.chupai.length>0) {
                this.showChupai(localIndex,seatData.chupai)
            }else if (seatData.folds&&seatData.folds.length>0) {
                this.showFolds(localIndex)
            }else{
                this.showHolds(localIndex,seatData.holds);
                // // 自己则显示配牌按钮
                if (localIndex==0) {
                    var chupaiBt=this.gameRoot.getChildByName("btnChu");
                    chupaiBt.active=true;
                    // 出牌按钮改变
                    this.changChuBt()
                }
            }
        }
    },
    setSpriteFrameByMJID:function(sprite,mjid){
        sprite.spriteFrame = cc.vv.mjmgr.getSpriteFrameByMJID(mjid)
    },
    // 发牌
    doFapai:function(){
        console.log("doFapai");
        // this.moveObj=[];
        // 获取坐席
        var seats = cc.vv.gameNetMgr.seats;
        // 开启遮罩
        this._zhezhao.active=true;
        // 四个人的手牌位置（后面移动节点是加在canvas里,位置按canvas基准x,y）
        var endArr=[
            [{x:-116,y:-255},{x:-40,y:-255},{x:37,y:-255},{x:113,y:-255}],
            [{x:439,y:-66},{x:483,y:-66},{x:527,y:-66},{x:571,y:-66}],
            [{x:-71,y:259},{x:-27,y:259},{x:17,y:259},{x:61,y:259}],
            [{x:-562,y:-65},{x:-518,y:-65},{x:-474,y:-65},{x:-430,y:-65}]
        ];
        // 发牌开始坐席
        var szone=cc.vv.gameNetMgr.szone;
        var sztwo=cc.vv.gameNetMgr.sztwo;
        var zhuangSeatIndex=cc.vv.gameNetMgr.button;
        // 从庄家数起，根据色子点数算发牌开始坐席(0/1/2/3)
        var seatIndex=(szone+sztwo+zhuangSeatIndex-1)%4-1;
        // 记录发牌坐席次(0/1/2/3)
        var seatCount=-1;
        var self=this;
        // 记录发牌个数
        var numCount=0;
        // 记录已经发牌的四个节点(每个玩家发牌结束时清除)
        var paiNodeArr=[];
        var fn=function(){
            // 改变计数
            seatIndex++;
            if (seatIndex>3) {
                seatIndex=0
            };
            seatCount++;
            if (seatCount>3) {
                return
            };
            var localIndex=cc.vv.gameNetMgr.getLocalIndex(seatIndex);
            // console.log("发下一家牌");
            for (var j = 0; j < 4; j++) {
                // console.log("seatCount",seatCount,"j",j,"seatIndex",seatIndex,"localIndex",localIndex);
                numCount++;
                // 获取要移动到的目标节点
                var end=endArr[localIndex][j];
                // 获取要移动的对象节点
                var start=self._paidui.children[seatCount*4+j];
                // 透明隐藏要发的牌
                start.opacity=0;
                // 复制发牌节点做移动效果（真正的牌节点有布局组件无法移动）
                var target=cc.instantiate(self._paiduiItem);
                paiNodeArr.push(target);
                self.node.addChild(target);
                target.x=start.x;
                target.y=start.y;
                // 保存发牌个数和坐席
                target.paiCount=numCount;
                target.seatIndex=seatIndex;
                target.localIndex=localIndex;
                self.doMoving(target,end,function(target){
                    // console.log("移动end");
                    // 每个人自己手牌发完则展示手牌
                    if (target.paiCount==4||target.paiCount==8||target.paiCount==12||target.paiCount==16) {
                        for (var i = 0; i < 4; i++) {
                            paiNodeArr[0].removeFromParent();
                            paiNodeArr.splice(0,1)  
                        };
                        // console.log("发完一家,展示手牌");
                        self.showHolds(target.localIndex,seats[target.seatIndex].holds);
                        if (target.paiCount==16) {
                            // 扣除底牌
                            // console.log("发牌结束");
                            for (var k = 0; k < 16; k++) {
                                self._paidui.removeChild(self._paidui.children[0])
                            };
                            // 关闭遮罩
                            self._zhezhao.active=false;
                            // 显示配牌按钮
                            var chupaiBt=self.gameRoot.getChildByName("btnChu");
                            chupaiBt.active=true;
                            self.changChuBt()
                        };
                        if (seatCount<3) {
                            //没发完四家才接着发牌
                            // console.log("继续发下家牌");
                            fn()
                        };
                    }
                })
            }
        };
        fn()
    },
    // 开局丢色子
    doSezi:function(){
        console.log("doSezi");
        cc.vv.audioMgr.playSFX("dice.mp3");
        var seziNode=this.gameRoot.getChildByName("sezi");
        seziNode.active=true;
        var szone=cc.vv.gameNetMgr.szone;
        var sztwo=cc.vv.gameNetMgr.sztwo;
        var szoneSprite=seziNode.children[0].getComponent(cc.Sprite);
        var sztwoSprite=seziNode.children[1].getComponent(cc.Sprite);
        // 两个色子切图频率不一样（增加效果）;
        var self=this;
        // 控制丢色子结束
        var numCount=0;
        var fn=function(){
            numCount++;
            if (numCount<70) {
                // 生成1-6随机数
                var numOne=Math.floor(Math.random()*6 + 1);
                szoneSprite.spriteFrame=cc.vv.mjmgr.getSeziSpriteFrameByNum(numOne);

                var numTwo=Math.floor(Math.random()*6 + 1);
                // console.log("第二色子随机数",numTwo);
                sztwoSprite.spriteFrame=cc.vv.mjmgr.getSeziSpriteFrameByNum(numTwo);

                setTimeout(fn,30)
            }else{
                szoneSprite.spriteFrame=cc.vv.mjmgr.getSeziSpriteFrameByNum(szone);
                sztwoSprite.spriteFrame=cc.vv.mjmgr.getSeziSpriteFrameByNum(sztwo);
                // 发牌
                setTimeout(function(){
                    seziNode.active=false;
                    self.doFapai()
                },1500)
            }
        };
        fn()
    },
    // 移动牌
    doMoving:function(obj,targetObj,callback){
        // 全部挂在obj上作为属性避免定时器混乱
        obj.callback=cc.callFunc(callback, obj);
        obj.endX=targetObj.x;
        obj.endY=targetObj.y;
        obj.action=cc.sequence(cc.moveTo(0.8, cc.p(obj.endX,obj.endY)), obj.callback);
        obj.runAction(obj.action)
    },
    // 翻牌
    addXuanzhuan:function(obj,callback){
        // 全部挂在obj上作为属性避免定时器混乱
        obj.children[1].active=true;
        obj.scaleX=1;
        obj.skewY=0;
        // 临界点
        obj.callbackZero=cc.callFunc(function(obj){
            obj.children[1].active=false
        }, obj);
        obj.callback=cc.callFunc(callback, obj);
        // 正到中
        obj.XuanZhuanAction1 = cc.spawn(cc.scaleTo(0.3,0,1), cc.skewTo(0.3,0,40));
        // 中到反
        obj.XuanZhuanAction2 = cc.spawn(cc.scaleTo(0.3,-1,1), cc.skewTo(0.3,0,0));
        obj.action=cc.sequence(obj.XuanZhuanAction1,obj.callbackZero,obj.XuanZhuanAction2,obj.callback);
        obj.runAction(obj.action)
    },
    // 从小到大放大效果
    doScale:function(obj){
        // 全部挂在obj上作为属性避免定时器混乱
        obj.scale=0;
        obj.action=cc.scaleTo(0.8, 1);
        obj.runAction(obj.action)
    },
    // 从显到隐
    doFadeOut:function(obj,time,callback){
        obj.callback=cc.callFunc(callback, obj);
        obj.time=time;
        obj.callbackRest=cc.callFunc(function(obj){obj.opacity=255}, obj);
        obj.action=cc.sequence(cc.fadeOut(obj.time), obj.callback,obj.callbackRest);
        obj.runAction(obj.action)
    },
    // 从隐到显
    doFadeIn:function(obj,time,callback){
        obj.opacity=0;
        obj.time=time;
        obj.callback=cc.callFunc(callback, obj);
        obj.action=cc.sequence(cc.fadeIn(obj.time), obj.callback);
        obj.runAction(obj.action)
    },
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {
        
    // },
    onDestroy:function(){
        // console.log("onDestroy");
        if(cc.vv){
            cc.vv.gameNetMgr.clear()   
        }
    }
});
